using Microsoft.AspNetCore.Mvc;
using PandaWebAPI.Interfaces;
using PandaWebAPI.Models.ef;

namespace PandaWebAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CartItemController : ControllerBase
    {
        private readonly ICartItemService _cartItemService;

        public CartItemController(ICartItemService cartItemService)
        {
            _cartItemService = cartItemService;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<CartItem>>> GetAllCartItems()
        {
            var cartItems = await _cartItemService.GetAllCartItemsAsync();
            return Ok(cartItems);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<CartItem>> GetCartItemById(Guid id)
        {
            var cartItem = await _cartItemService.GetCartItemByIdAsync(id);
            if (cartItem == null)
                return NotFound();

            return Ok(cartItem);
        }

        [HttpGet("user/{userId}")]
        public async Task<ActionResult<IEnumerable<CartItem>>> GetCartItemsByUserId(Guid userId)
        {
            var cartItems = await _cartItemService.GetCartItemsByUserIdAsync(userId);
            return Ok(cartItems);
        }

        [HttpPost]
        public async Task<ActionResult<CartItem>> CreateCartItem(CartItem cartItem)
        {
            try
            {
                var createdCartItem = await _cartItemService.CreateCartItemAsync(cartItem);
                return CreatedAtAction(nameof(GetCartItemById), new { id = createdCartItem.CartItemId }, createdCartItem);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpPut("{id}")]
        public async Task<ActionResult<CartItem>> UpdateCartItem(Guid id, CartItem cartItem)
        {
            if (id != cartItem.CartItemId)
                return BadRequest("ID mismatch");

            try
            {
                var updatedCartItem = await _cartItemService.UpdateCartItemAsync(cartItem);
                return Ok(updatedCartItem);
            }
            catch (KeyNotFoundException)
            {
                return NotFound();
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteCartItem(Guid id)
        {
            var result = await _cartItemService.DeleteCartItemAsync(id);
            if (!result)
                return NotFound();

            return NoContent();
        }

        [HttpDelete("user/{userId}")]
        public async Task<ActionResult> ClearUserCart(Guid userId)
        {
            var result = await _cartItemService.ClearUserCartAsync(userId);
            if (!result)
                return NotFound();

            return NoContent();
        }
    }
} 